package com.iotechn.unimall.admin.api.purchaseOrder;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.iotechn.unimall.core.exception.AdminServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.domain.CategoryDO;
import com.iotechn.unimall.data.domain.PurchaseOrderGoodsDO;
import com.iotechn.unimall.data.dto.purchase.PurchaseOrderGoodsDTO;
import com.iotechn.unimall.data.mapper.CategoryMapper;
import com.iotechn.unimall.data.mapper.PurchaseOrderGoodsMapper;
import com.iotechn.unimall.data.model.Page;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class PurchaseOrderGoodsServiceImpl implements PurchaseOrderGoodsService {
    @Autowired
    private PurchaseOrderGoodsMapper purchaseOrderGoodsMapper;
    @Autowired
    private CategoryMapper categoryMapper;

     @Override
        public Page<PurchaseOrderGoodsDO> list(Integer page, Integer limit, Long adminId) throws ServiceException {
            Wrapper<PurchaseOrderGoodsDO> wrapper = new EntityWrapper<PurchaseOrderGoodsDO>();
            /**if (!StringUtils.isEmpty(name)) {
                wrapper.like("username", name);
            }**/
            wrapper.orderBy("id", false);
            Integer count = purchaseOrderGoodsMapper.selectCount(wrapper);
            List<PurchaseOrderGoodsDO> PurchaseOrderGoodsDOS = purchaseOrderGoodsMapper.selectPage(new RowBounds((page - 1) * limit, limit), wrapper);
            return new Page<>(PurchaseOrderGoodsDOS, page, limit, count);
        }

        @Override
        @Transactional(rollbackFor = Exception.class)
        public PurchaseOrderGoodsDO create(PurchaseOrderGoodsDO purchaseOrderGoodsDO, Long adminId) throws ServiceException {
            Date now=new Date();
            purchaseOrderGoodsDO.setGmtCreate(now);
            purchaseOrderGoodsDO.setGmtUpdate(now);
            if (purchaseOrderGoodsMapper.insert(purchaseOrderGoodsDO) > 0) {
                purchaseOrderGoodsDO.setId(purchaseOrderGoodsDO.getId());
                return purchaseOrderGoodsDO;
            }
             throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
        }

        @Override
        @Transactional(rollbackFor = Exception.class)
        public String update(PurchaseOrderGoodsDO purchaseOrderGoodsDO, Long adminId) throws ServiceException {
            Long id = purchaseOrderGoodsDO.getId();
            if (id == null) {
               return "fail";
            }
            Date now=new Date();
            purchaseOrderGoodsDO.setGmtUpdate(now);
            if (purchaseOrderGoodsMapper.updateById(purchaseOrderGoodsDO) > 0) {
                return "ok";
            }
            throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
     }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String delete(Long id, Long adminId) throws ServiceException {
        if (purchaseOrderGoodsMapper.deleteById(id) > 0) {
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);

     }

    @Override
    public PurchaseOrderGoodsDO detail(Long id, Long adminId) throws ServiceException {
       return purchaseOrderGoodsMapper.selectById(id);
    }


    @Override
    public Page querySkusByWarehouseId(Integer page, Integer limit, Long warehouseId, String skuIds, String search) {
        LinkedList<Long> childrenIds = new LinkedList<>();
//         if(!StringUtils.isEmpty(skuIds)){
//             String[] spuIdArr=skuIds.split(",");
//             skuIdLists= Arrays.asList(spuIdArr);
//         }
        if (skuIds != null && !"".equals(skuIds)) {
            List<CategoryDO> childrenList = categoryMapper.selectList(new EntityWrapper<CategoryDO>().eq("parent_id", skuIds));
            // 传入类目拥有的三级类目集合

            // 传入类目没有子类目
            if (CollectionUtils.isEmpty(childrenList)) {
                // 则传入类目为三级类目
                childrenIds.add(Long.valueOf(skuIds));
            } else {

                CategoryDO categoryDO = categoryMapper.selectById(skuIds);

                // 检验传入类目是一级还是二级类目
                if (categoryDO.getParentId() != 0L) {
                    //二级分类
                    childrenList.forEach(item -> {
                        childrenIds.add(item.getId());
                    });
                } else {
                    //一级分类
                    childrenList.forEach(item -> {
                        List<CategoryDO> leafList = categoryMapper.selectList(new EntityWrapper<CategoryDO>().eq("parent_id", item.getId()));
                        if (!CollectionUtils.isEmpty(leafList)) {
                            leafList.forEach(leafItem -> {
                                childrenIds.add(leafItem.getId());
                            });
                        }
                    });
                }
            }

        }
        Integer start = (page - 1) * limit;
        Integer end = limit;


        List<PurchaseOrderGoodsDTO> purchaseWarehouseOrderGoodsDTOS = purchaseOrderGoodsMapper.querySkusByWarehouseId(warehouseId, childrenIds, start, end, search);
        Integer count = purchaseOrderGoodsMapper.countSkusByWarehouseId(warehouseId, childrenIds, search);
        return new Page<>(purchaseWarehouseOrderGoodsDTOS, page, limit, count);
    }

    @Override
    public List<Map<String, Object>> listWarehouseSkusByPara(Long pOrderId) throws ServiceException {
        List<Map<String, Object>> result = purchaseOrderGoodsMapper.selectMaps(new EntityWrapper<PurchaseOrderGoodsDO>()
                .eq(pOrderId != null, "p_order_id", pOrderId)
                .setSqlSelect("id","p_goods_buy_num as pGoodsBuyNum", "p_goods_price as pGoodsPrice", "goods_name as goodsName", "bar_code as barCode", "goods_img as img",
                        "goods_unit as unit", "p_goods_amount as pGoodsAmount",
                        "spu_id as spuId", "spu_name as spuName", "sku_id as skuId", "sku_name as skuName"));
        //处理价格
        result.stream().map(i -> {

            Float originalGoodPrice = Float.valueOf(String.valueOf(i.get("pGoodsPrice")));
            i.put("pGoodsPrice", originalGoodPrice / 100);
            Float pGoodsAmount = Float.valueOf(String.valueOf(i.get("pGoodsAmount")));
            i.put("pGoodsAmount", pGoodsAmount / 100);
            return i;
        }).collect(Collectors.toList());
        return result;

    }





}